//
//  CYSlider.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/6/2.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class CYSlider: UISlider {
    let thumbBound_x = 10
    let thumbBound_y = 20
    var lastBounds:CGRect?
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {
//        let newRect = CGRect(x: rect.origin.x - 10, y: rect.origin.y, width: rect.size.width + 20, height: rect.size.height)
        var temprect = rect
        temprect.origin.x = rect.origin.x - 10
        temprect.size.width = rect.size.width + 20
        lastBounds = super.thumbRect(forBounds: bounds, trackRect: temprect, value: value)
        return super.thumbRect(forBounds: bounds, trackRect: temprect, value: value)
    }
    
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let result = super.hitTest(point, with: event)
        if point.x < 0 || point.x > self.bounds.size.width {
            return result
        }
        if -CGFloat(thumbBound_y) <= point.y  && point.y <  (lastBounds?.size.height)! + CGFloat(thumbBound_y) {
            var value = 0.0
            value = Double(point.x - self.bounds.origin.x)
            value = value / Double(self.bounds.size.width)
            value = value < 0 ? 0 : value
            value = value > 1 ? 1 : value
            value = Double(CGFloat(value) * CGFloat((self.maximumValue - self.minimumValue)) + CGFloat(self.minimumValue))
            
            self.setValue(Float(value), animated: true)
        }
        
        return result
    }
    
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        var result = super.point(inside: point, with: event)
        if !result && point.y > -10 {
            let bool1 = point.x >= (lastBounds?.origin.x)! - CGFloat(thumbBound_x)
            let bool2 = point.x <= (lastBounds?.origin.x)! + (lastBounds?.size.width)! + CGFloat(thumbBound_x)
            let bool3 = point.y < (lastBounds?.size.height)! + CGFloat(thumbBound_y)
            if bool1 && bool2 && bool3 {
                result = true
            }
        }
        return result
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
